#!/usr/bin/perl

#use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;

my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;

if (@ARGV <= 0) {
  print "A directory is required to run a GET command.  Example usage:\n  perl $0 http://yourhost/addama-rest/myRepo/path/myPath /outpath/outfile.dat\n";
  exit(0);
}
my ($url,$outfile) = @ARGV;

my $json = new JSON;
my $obj;
getUrl($url);

sub getUrl {
  my ($url) = @_;
  if($url) {
      my $response = $browser->get($url);

      if ($response->is_success) {
          #open(OUTP, $outfile);
          open FILE, ">$outfile" or die $!;
          print("Success on getting response\n");
          my $content = $response->content;
          #my $content = $response->content;
          my $json_text = $json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);
          my $dir_num = 0;
          foreach my $directories(@{$json_text->{directories}}){
            if ($dir_num == 0){
                print(FILE "Addama_Directories\n");
             }
             print("$directories->{'host-url'}/addama-rest/$directories->{repository}/path$directories->{path}\n");
             print(FILE "$directories->{'host-url'}/$directories->{repository}/path$directories->{path}\n");
             $dir_num++;
         }
         $file_num = 0;
         foreach my $files(@{$json_text->{files}}){
             if ($file_num == 0){
                print(FILE "Addama_Files\n");
             }
             print("$files->{'host-url'}/addama-rest/$files->{repository}/path$files->{path}\n");
             print(FILE "$files->{'host-url'}/$files->{repository}/path$files->{path}\n");
             $file_num++;
        }
        close (FILE);

          # eval in case response isn't legit json
          eval { $obj = $json->decode($content) };
      }
      else {
          if($response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
          } else {
            die $response->status_line;
          }
      }
  }
}
